package com.blog.wu.myblog.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.NetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.blog.wu.myblog.entity.Role;
import com.blog.wu.myblog.entity.TestUser;
import com.blog.wu.myblog.entity.UserInfo;
import com.blog.wu.myblog.redis.RedisService;
import com.blog.wu.myblog.service.UserInfoService;
import com.blog.wu.myblog.util.PropertiesLoader;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.logging.log4j.message.SimpleMessage;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.ResourceLoader;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Author wuyanshen
 * @Date 2, 018-10-18 下午10:20
 * @Discription 描述
 */
@Controller
@RequestMapping("/")
public class TestController {

    private static int TOTAL_COUNT = 0;

    private static PropertiesLoader loader = new PropertiesLoader("blog.properties");
    private static Map<String, String> map = new HashMap<>();

    @Value("${server.port}")
    private String port;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private RedisService redisService;


    @RequestMapping("count")
    public String getCount() {
        return TOTAL_COUNT + "";
    }

    @RequestMapping("add")
    public void countAdd() {
        TOTAL_COUNT++;
    }

    @RequestMapping("del")
    public void countDel() {
        TOTAL_COUNT--;
        if (TOTAL_COUNT < 0) {
            TOTAL_COUNT = 0;
        }
    }

    @RequestMapping("set/{val}")
    public String countDel(@PathVariable(value = "val") int val) {
        TOTAL_COUNT = val;
        return TOTAL_COUNT + "";
    }

    @RequestMapping("t/uuid")
    @ResponseBody
    public String uuid() {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        return uuid;
    }

//    @RequestMapping("")
//    public String toLogin() {
//        return "redirect:back/user/loadLogin";
//    }

    @RequestMapping("user")
    public String user(TestUser user, Model model) {
        model.addAttribute("user", user);
        return "back/testUser";
    }




    public static void msg(String... msg) {
        for (String str : msg) {
            map.put(str, str);
        }
    }

    /**
     * 获取配置
     */
    public static String getConfig(String key) {
        String value = map.get(key);
        if (value == null) {
            value = loader.getProperty(key);
            map.put(key, value != null ? value : StringUtils.EMPTY);
        }
        return value;
    }

    //注解的使用
    @RequiresRoles("admin")
    @RequiresPermissions("create")
    @RequestMapping(value = "create")
    public String create() {
        return "Create success!";
    }


    /**
     * @param data
     * @RequestBody这个注解在一个方法中只能绑定到一个参数上，如果绑定多个就会报错如 （@RequestBody String name,@RequestBody String age）
     * @Date 2018/11/20 4:34 PM
     * @Author wuyanshen
     */
    @RequestMapping(value = "t/login", method = RequestMethod.POST)
    @ResponseBody
    public Map user(@RequestBody String data) {
        JSONObject jsonobj = JSONObject.parseObject(data);
        String username = jsonobj.getString("username");
        String password = jsonobj.getString("password");
        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", "success");
        map.put("password", password);
        map.put("username", username);
        return map;
    }

    @RequestMapping(value = "t/test", method = RequestMethod.GET)
    @ResponseBody
    public String test() {
        return "当前项目端口是：" + port;
    }


    /**
     * 测试跨域
     *
     * @Date 2018/12/21 1:26 PM
     * @Author wuyanshen
     */
    @RequestMapping(value = "t/kuayu", method = RequestMethod.GET)
    public String kuayu() {
        return "back/testUser";
    }


    @Autowired
    private JavaMailSender javaMailSender;

    @RequestMapping(value = "t/sendEmail", method = RequestMethod.GET)
    public String sendEmail() {
        SimpleMailMessage simpleMessage = new SimpleMailMessage();
        simpleMessage.setFrom("wuys@elisoft.com.cn");
        simpleMessage.setTo("763010522@qq.com");
        simpleMessage.setSubject("嗨喽");
        simpleMessage.setText("圣诞节快乐哟~");
        javaMailSender.send(simpleMessage);

        return "1";
    }

    @RequestMapping(value = "t/user", method = RequestMethod.GET)
    @ResponseBody
    public List<String> user() {
        UserInfo userInfo = new UserInfo();
        userInfo.setId("12");
//        UserInfo user = userInfoService.get(userInfo);
//        return user;
        List<String> list = userInfoService.findUserRole(userInfo);
        return list;
    }


    /**
     * 清除ehcache缓存
     *
     * @param
     * @return java.lang.String
     * @Date 2018/12/28 10:13 PM
     * @Author wuyanshen
     */
    @RequestMapping(value = "t/clean", method = RequestMethod.GET)
    @ResponseBody
    public String clean() {
        cacheManager.getCache("baseCache").clear();
        return "success";
    }

    /**
     * redis存String
     *
     * @param key
     * @param value
     * @return java.lang.String
     * @Date 2019/1/3 3:26 PM
     * @Author wuyanshen
     */
    @RequestMapping(value = "t/redis/{key}/{value}",method = RequestMethod.GET)
    @ResponseBody
    public String redisString(@PathVariable("key") String key,@PathVariable("value") String value) {
        this.redisService.setString(key,value,120L);
        return "success";
    }

    @RequestMapping(value = "t/redis/remove/{key}",method = RequestMethod.GET)
    @ResponseBody
    public String remove(@PathVariable("key") String key) {
        this.redisService.remove(key);
        return "remove success";
    }



    public static void main(String[] args) {
//        String str = getConfig("msg");
//        System.out.println(str);

//        msg("a", "b", "c", "d");
//        System.out.println(map.keySet().toString());
        String id = "140623199308230012";
        boolean id_18 = IdcardUtil.isValidCard(id);
        if (id_18) {
            System.out.println("合法的身份证");
        } else {
            System.out.println("不合法");
        }

        System.out.println(IdUtil.simpleUUID());

        LinkedHashSet<String> linkedHashSet =  NetUtil.localIpv4s();
        for (String s : linkedHashSet) {
            System.out.println(s);
        }

        if (NetUtil.isValidPort(6379)) {
            System.out.println("有效端口");
        } else {
            System.out.println("无效端口");
        }

        String str = new String("123");

        if (ObjectUtil.isNull(str)) {
            System.out.println("是空");
        } else {
            System.out.println("不是空");
        }

        String url = "http://localhost:3001/qrCodeUrl";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("agentSn", "1799a5edac854b8dbe4cf81337bca748");
        String result = HttpUtil.get(url, paramMap);
        System.out.println(result);

    }

}
